<template>
    <div class="mapbox-maps" >
        <div id="map" style="position: relative">  
            <i class="el-icon-s-unfold" style="position: absolute; left: 0px; top: 10px; z-index: 2;font-size:25px" @click="drawer = true"></i>
            <el-drawer style="z-index: 2;"
                title="参数设置"
                :visible.sync="drawer"
                :append-to-body="true"
                :modal="false"
                size="35%">
                <div class="demo-drawer__content" style="padding:10px">
                    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                        <el-form-item label="分析名称" prop="name">
                            <el-input v-model="ruleForm.name" placeholder="请选择分析名称"></el-input>
                        </el-form-item>
                        <el-form-item label="分析对象" prop="region">
                            <el-select v-model="ruleForm.region" placeholder="请选择分析对象">
                            <el-option label="检测有效性" value="valid"></el-option>
                            <el-option label="检测简单性" value="simple"></el-option>
                            <el-option label="多图层分析" value="many"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item v-if="ruleForm.region =='valid'" label="目标数据" prop="delivery">
                            <el-input v-model="ruleForm.oneTable" placeholder="请输入目标数据"></el-input>
                        </el-form-item>
                        <el-form-item v-if="ruleForm.region =='simple'" label="目标数据" prop="delivery">
                            <el-input v-model="ruleForm.oneTable" placeholder="请输入目标数据"></el-input>
                        </el-form-item>
                        <el-form-item v-if="ruleForm.region =='many'" label="输入数据" prop="delivery">
                            <el-input v-model="ruleForm.srcTable" placeholder="请输入数据"></el-input>
                        </el-form-item>
                        <el-form-item v-if="ruleForm.region =='many'" label="被输入数据" prop="delivery">
                            <el-input v-model="ruleForm.newTable" placeholder="请输入数据"></el-input>
                        </el-form-item>
                        <el-form-item v-if="ruleForm.region =='many'" label="输入距离" prop="delivery">
                            <el-input v-model="ruleForm.radius" placeholder="请输入距离"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
                            <el-button @click="resetForm('ruleForm')">重置</el-button>
                        </el-form-item>
                    </el-form>
                </div>  
            </el-drawer>
        </div>       
    </div>   
</template>
<script>
export default{
    name:'PostgisSpaceRelation',
    data(){
      return{
        geojson: {        
          type:'geojson',
          data:{
          "type": "FeatureCollection",
          "features":[]
          }
        },
        drawer: false,
        ruleForm: {
          name: '',
          region: '',
          oneTable:'',
          srcTable:'',
          newTable:'',
          radius:''
        },
        rules: {
          name: [
            { required: true, message: '请输入活动名称', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          region: [
            { required: true, message: '请选择活动区域', trigger: 'change' }
          ],
        }
       
      }
    },
    mounted() {
      this.loadMap()
    },
    beforeDestroy(){
      this.map.remove()

    },
    methods:{
        
      loadMap() {
        // 英文标注转换为中文   
        // mapboxgl.setRTLTextPlugin(
        //   "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.1.0/mapbox-gl-rtl-text.js"
        // );
        this.map =  new mapboxgl.Map({
            accessToken: 'pk.eyJ1Ijoienh0d24iLCJhIjoiY2wzanV3bHduMTZwejNrcXcyd3B1bzBieiJ9.aW_TDqLomftwPvBu7OWqwQ',
            container: 'map',
            style: 'mapbox://styles/mapbox/outdoors-v10', // stylesheet location
            center: [116.9,32.8],//[116.790759959,32.654110234],//[113.899878,22.592338],  //[116.79507,32.65542], // starting position [lng, lat]
            zoom: 8, // starting zoom
            hash: false,
            //pitch: 45,  //地图的角度，不写默认是0，取值是0-60度，一般在3D中使用
            bearing: 0, //地图的初始方向，值是北的逆时针度数，默认是0，即是正北
            antialias: true, //抗锯齿，通过false关闭提升性能
            projection: "globe",
        })
        // 设置语言
        // var language = new MapboxLanguage({ defaultLanguage: "zh" });
        // this.map.addControl(language);

        //地图导航
        var nav = new mapboxgl.NavigationControl();
        this.map.addControl(nav, 'top-right');

        // 比例尺
        var scale = new mapboxgl.ScaleControl({
            maxWidth: 100,
            unit: "metric"
        });
        this.map.addControl(scale,"bottom-left");

        // 全图
        this.map.addControl(new mapboxgl.FullscreenControl());
        // 定位
        this.map.addControl(
            new mapboxgl.GeolocateControl({
            positionOptions: {
                enableHighAccuracy: true
            },
            trackUserLocation: true
            })
        );
        let that = this;
        this.map.on('load',function () {
          that.map.setFog({
            color: "rgb(186, 210, 235)",
            'high-color': 'rgb(36, 92, 223)', 
            'horizon-blend': 0.02, 
            'space-color': 'rgb(11, 11, 25)', 
            'star-intensity': 0.6 
          });
          console.log(that)
          that.map.addSource("geojson_point",that.geojson);
          that.map.addSource("geojson_line",that.geojson);
          that.map.addSource("geojson_polygon",that.geojson);
          that.map.addSource("grid_line",that.geojson);
          that.map.addSource("interpolation",that.geojson);
          that.map.addSource("center",that.geojson);
          that.map.addLayer({			   
            "id": "geojson_polygon",
            "type": "fill",
            "source": "geojson_polygon",              
            "layout": {
              "visibility": "visible",			
            },
            "paint": {
              "fill-color":"#E43961",
              'fill-opacity': 1,
            }
          })
          that.map.addLayer({
            "id": "geojson_line",
            "type": "line",
            "source": "geojson_line",              
            "layout": {
              "visibility": "visible",			
            },
            "paint": {
              "line-opacity": 1,
              "line-color": "#000000",
              "line-width": 1,				
            }                 
          })  
          that.map.addLayer({
            "id": "geojson_text",
            "type": "symbol",
            "source": "geojson_polygon",              
            "layout": {
              "visibility": "visible",			
              'text-field': '{ct}',		
              'text-size': 12
            },
            paint: {
              'text-halo-color': '#0000FF',
              //'text-halo-width': 2
            }
          })             
          that.map.addLayer({
              id: "geojson_point",
              type: "circle",
              source: "geojson_point",
              paint: {
                  "circle-radius": 2,
                  "circle-color": "#00A54E",
              }
          }); 
          that.map.addLayer({
            "id": "geojson_grid_line",
            "type": "line",
            "source": "grid_line",              
            "layout": {
              "visibility": "visible",			
            },
            "paint": {
              "line-opacity": 1,
              "line-color": "#FF0088",
              "line-width": 1,				
            }                 
          })  
          that.map.addLayer({
              id: "interpolation_point",
              type: "circle",
              source: "interpolation",
              paint: {
                  "circle-radius": 3,
                  "circle-color": "#A20055",
              }
          }); 
          that.map.addLayer({
            "id": "interpolation_line",
            "type": "line",
            "source": "interpolation",              
            "layout": {
              "visibility": "visible",			
            },
            "paint": {
              "line-opacity": 1,
              "line-color": "#7700FF ",
              "line-width": 1,				
            }                 
          }) 	
          that.map.addLayer({
            "id": "interpolation_text",
            "type": "symbol",
            "source": "interpolation",              
            "layout": {
              "visibility": "visible",			
              'text-field': '{weigthfield}',		
              'text-size': 12
            },
            paint: {
              'text-halo-color': '#FF3333',
              //'text-halo-width': 2
            }
          })   	
          that.map.addLayer({
              id: "center_point",
              type: "circle",
              source: "center",
              paint: {
                  "circle-radius": 3,
                  "circle-color": "#FF0000",
              }
          });
          // that.loadLine()
          // that.loadPoint()
            
        })          
      },  
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let that = this           
            let fd =  new URLSearchParams()
            fd.append("oneTable",that.ruleForm.oneTable) 
            let url = that.ruleForm.region == 'simple'  ? "/topology/simple" :
             that.ruleForm.region == 'valid' ? "/topology/valid" : "/topology/many"
            that.$axios.post(url, fd)       
            .then(function (res) {          
              console.log(res)
              let features = []
              res.data.data.forEach(e=>{
                let geom = JSON.parse(e.row_to_json.value)    
                features=geom.features              
              })
              that.map.getSource('geojson_line').setData({
                  "type": "FeatureCollection",
                  "features":[]
              })
              that.map.getSource('geojson_line').setData({
                  "type": "FeatureCollection",
                  "features":features
              })
            })
            .catch(function (error) {       
              console.log(error);
            })             
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      /**
       * 
       * 加载点数据
       * 
       */
      loadPoint(){
        debugger
        let that = this
        // that.$refs["newParameter"].validate((valid) => {       
        //   if (valid) {
            // let that = this           
           let fd =  new URLSearchParams()
            fd.append("srcTable","shenzhen_2005")                               
            let url = "/analysis/geojson"                           
            that.$axios.post(url, fd)       
            .then(function (res) {          
              console.log(res)
              let features = []
              res.data.data.forEach(e=>{
                let geom = JSON.parse(e.geom)    
                features.push({
                  "type": "Feature",
                  "geometry":geom,
                  "properties": {"status": "status"}
                })	                        
              })
              that.map.getSource('geojson_point').setData({
                  "type": "FeatureCollection",
                  "features":[]
              })
              that.map.getSource('geojson_point').setData({
                  "type": "FeatureCollection",
                  "features":features
              })
            })
            .catch(function (error) {       
              console.log(error);
            })             
        //   } else {
        //     console.log('error submit!!');
        //     return false;
        //   }
        // });                
      },	

      /**
      * 渲染线数据
      * 
      */
      loadLine(){
        debugger
        let that = this
        // that.$refs["newParameter"].validate((valid) => {       
        //   if (valid) {
            // let that = this           
           let fd =  new URLSearchParams()
            fd.append("srcTable","zd")                               
            let url = "/analysis/geojson"                           
            that.$axios.post(url, fd)       
            .then(function (res) {          
              console.log(res)
              let features = []
              res.data.data.forEach(e=>{
                let geom = JSON.parse(e.geom)    
                features.push({
                  "type": "Feature",
                  "geometry":geom,
                  "properties": {"status": "status"}
                })	                        
              })
              that.map.getSource('geojson_polygon').setData({
                  "type": "FeatureCollection",
                  "features":[]
              })
              that.map.getSource('geojson_polygon').setData({
                  "type": "FeatureCollection",
                  "features":features
              })
            })
            .catch(function (error) {       
              console.log(error);
            })             
        //   } else {
        //     console.log('error submit!!');
        //     return false;
        //   }
        // });                
      },	
     
   
    }
}

</script>
<style scoped lang="scss">
 @import "../../../public/mapbox/mapbox-gl.css";
 .mapbox-maps {
    width: 100%;
    height: calc(100vh - 50px);
    position: relative;
    #map {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        bottom:0;
        right: 0;        
    }
    
}
.mapboxgl-canvas {
    outline: none;
}
  /* 隐藏mapbox商标 */
.mapboxgl-ctrl-logo {
    display: none;
} 
.jv-container .jv-code.boxed {
    max-height: 100%;
}
</style>